<template>
  <div>
    <!-- 顶部栏开始 -->
    <van-nav-bar
      class="addtopnav"
      title="我的收货地址"
      left-text="返回"
      right-text="删除"
      left-arrow
      fixed
      placeholder
      @click-left="onClickLeft"
      @click-right="ondel"
    />
    <!-- 顶部栏结束 -->

    <!-- 地址管理开始 -->
    <div class="address">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        add-button-text="+ 新增地址"
        @add="onAdd"
        @edit="onEdit"
        @select="selectaddress"
      />
    </div>
    <!-- 地址管理结束 -->

    <!-- 新增地址 -->
  </div>
</template>

<script>
import { Get, Post } from "../gp";
import { Delete } from "../gp";
export default {
  data() {
    return {
      chosenAddressId: "1",
      list: [],
      selectaddressid:''
    };
  },
  mounted() {
    let data = {};
    data.user_id = sessionStorage.getItem("id");
    Post("/addr", data).then((result) => {
      if (result.data.code == 200) {
        let data = result.data.data;
        for (let i in data) {
          let newaddrlist = {
            id: data[i].did,
            name: data[i].receiver,
            tel: data[i].cellphone,
            areacode: data[i].areacode,
            address: `${data[i].province}${data[i].city}${data[i].area}${data[i].addr}`,
            isDefault: Boolean(data[i].is_default),
          };
          this.list.push(newaddrlist);
        }
      } else {
        alert("请稍后重试~");
      }
    });
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    onAdd() {
      this.$router.push("/addaddr");
    },
    onEdit(item) {
      this.$router.push({
        name: "Addedit",
        params: {
          id: item.id,
          name: item.name,
          tel: item.tel,
          province: item.province,
          city: item.city,
          county: item.area,
          addressDetail: item.address,
          areaCode: item.areacode,
        },
      });
    },
    selectaddress(item, index) {
      console.log(item, index);
      console.log(item.address);
      this.selectaddress = item.address;
      // sessionStorage.setItem('addr',this.selectaddress)
    },
    ondel() {
      let data = {};
      Delete(`/addr/delete/${this.selectaddressid}`, data).then((result) => {
        console.log(result);
        if (result.data.code == 200) {
          this.$Toast.success("删除成功");
          this.$router.push("/address");
        } else {
          this.$Toast.fail("删除失败");
        }
      });
    },
  },
};
</script>
<style lang="scss">
@import "../assets/scss/address.scss";
</style>